#include "advanceddialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGroupBox>
#include <QHeaderView>
#include <QLabel>
#include <QMessageBox>
#include <QDialog>
#include <QRegularExpression>
#include <QGridLayout>
#include <QEvent>

AdvancedDialog::AdvancedDialog(QWidget *parent) : QDialog(parent) {
    setWindowFlags(windowFlags() & ~Qt::WindowMaximizeButtonHint);
    // setWindowFlags((windowFlags() & ~Qt::WindowMaximizeButtonHint & ~Qt::WindowMinimizeButtonHint) | Qt::Dialog | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
    setupUi();
    // setFixedSize(this->size());
}

void AdvancedDialog::setupUi() {
    setWindowTitle("高级 TCP/IP 设置");
    resize(520, 400);
    QFont normalFont("Microsoft YaHei UI", 9);
    this->setFont(normalFont);
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    tabWidget = new QTabWidget(this);
    tabWidget->setFont(normalFont);
    // IP设置Tab
    ipTab = new QWidget(this);
    ipTab->setFont(normalFont);
    QVBoxLayout *ipTabLayout = new QVBoxLayout(ipTab);
    // IP地址
    QGroupBox *ipGroup = new QGroupBox("IP地址(R)", ipTab);
    ipGroup->setFont(normalFont);
    QVBoxLayout *ipGroupLayout = new QVBoxLayout(ipGroup);
    ipTable = new QTableWidget(0, 2, ipGroup);
    ipTable->setFont(normalFont);
    ipTable->horizontalHeader()->setFont(normalFont);
    ipTable->setHorizontalHeaderLabels({"IP地址", "子网掩码"});
    ipTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ipTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ipTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    QHBoxLayout *ipBtnLayout = new QHBoxLayout;
    btnAddIp = new QPushButton("添加(A)...", ipGroup);
    btnAddIp->setFont(normalFont);
    btnEditIp = new QPushButton("编辑(E)...", ipGroup);
    btnEditIp->setFont(normalFont);
    btnDeleteIp = new QPushButton("删除(V)", ipGroup);
    btnDeleteIp->setFont(normalFont);
    ipBtnLayout->addWidget(btnAddIp);
    ipBtnLayout->addWidget(btnEditIp);
    ipBtnLayout->addWidget(btnDeleteIp);
    ipGroupLayout->addWidget(ipTable);
    ipGroupLayout->addLayout(ipBtnLayout);
    // 网关
    QGroupBox *gwGroup = new QGroupBox("默认网关(F)", ipTab);
    gwGroup->setFont(normalFont);
    QVBoxLayout *gwGroupLayout = new QVBoxLayout(gwGroup);
    gatewayTable = new QTableWidget(0, 2, gwGroup);
    gatewayTable->setFont(normalFont);
    gatewayTable->horizontalHeader()->setFont(normalFont);
    gatewayTable->setHorizontalHeaderLabels({"网关", "跃点数/自动"});
    gatewayTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    gatewayTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    gatewayTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    QHBoxLayout *gwBtnLayout = new QHBoxLayout;
    btnAddGateway = new QPushButton("添加(D)...", gwGroup);
    btnAddGateway->setFont(normalFont);
    btnEditGateway = new QPushButton("编辑(T)...", gwGroup);
    btnEditGateway->setFont(normalFont);
    btnDeleteGateway = new QPushButton("删除(M)", gwGroup);
    btnDeleteGateway->setFont(normalFont);
    gwBtnLayout->addWidget(btnAddGateway);
    gwBtnLayout->addWidget(btnEditGateway);
    gwBtnLayout->addWidget(btnDeleteGateway);
    gwGroupLayout->addWidget(gatewayTable);
    gwGroupLayout->addLayout(gwBtnLayout);
    // 自动跃点
    QHBoxLayout *metricLayout = new QHBoxLayout;
    checkAutoMetric = new QCheckBox("自动跃点(U)", ipTab);
    checkAutoMetric->setFont(normalFont);
    checkAutoMetric->setChecked(true);
    QLabel *labelMetric = new QLabel("接口跃点数(N):", ipTab);
    labelMetric->setFont(normalFont);
    editMetric = new QLineEdit(ipTab);
    editMetric->setFont(normalFont);
    editMetric->setEnabled(false);
    metricLayout->addWidget(checkAutoMetric);
    metricLayout->addWidget(labelMetric);
    metricLayout->addWidget(editMetric);
    metricLayout->addStretch();
    // 组装
    ipTabLayout->addWidget(ipGroup);
    ipTabLayout->addWidget(gwGroup);
    ipTabLayout->addLayout(metricLayout);
    ipTab->setLayout(ipTabLayout);
    tabWidget->addTab(ipTab, "IP设置");
    mainLayout->addWidget(tabWidget);
    // 底部按钮
    QHBoxLayout *btnLayout = new QHBoxLayout;
    QPushButton *btnOk = new QPushButton("确定", this);
    btnOk->setFont(normalFont);
    QPushButton *btnCancel = new QPushButton("取消", this);
    btnCancel->setFont(normalFont);
    btnLayout->addStretch();
    btnLayout->addWidget(btnOk);
    btnLayout->addWidget(btnCancel);
    mainLayout->addLayout(btnLayout);
    // 信号槽
    connect(btnOk, &QPushButton::clicked, this, &QDialog::accept);
    connect(btnCancel, &QPushButton::clicked, this, &QDialog::reject);
    connect(btnAddIp, &QPushButton::clicked, this, &AdvancedDialog::onAddIp);
    connect(btnEditIp, &QPushButton::clicked, this, &AdvancedDialog::onEditIp);
    connect(btnDeleteIp, &QPushButton::clicked, this, &AdvancedDialog::onDeleteIp);
    connect(btnAddGateway, &QPushButton::clicked, this, &AdvancedDialog::onAddGateway);
    connect(btnEditGateway, &QPushButton::clicked, this, &AdvancedDialog::onEditGateway);
    connect(btnDeleteGateway, &QPushButton::clicked, this, &AdvancedDialog::onDeleteGateway);
    connect(checkAutoMetric, &QCheckBox::toggled, this, &AdvancedDialog::onAutoMetricToggled);
    // IP表格双击编辑
    connect(ipTable, &QTableWidget::itemDoubleClicked, this, [this](QTableWidgetItem*) {
        onEditIp();
    });
    // 网关表格双击编辑
    connect(gatewayTable, &QTableWidget::itemDoubleClicked, this, [this](QTableWidgetItem*) {
        onEditGateway();
    });
    // 初始化
    refreshIpTable();
    refreshGatewayTable();
}

void AdvancedDialog::setIpMode(IpMode mode) {
    ipMode = mode;
    refreshIpTable();
    btnAddIp->setEnabled(ipMode == Manual);
    btnEditIp->setEnabled(ipMode == Manual);
    btnDeleteIp->setEnabled(ipMode == Manual);
    // 网关按钮也根据模式控制
    btnAddGateway->setEnabled(ipMode == Manual);
    btnEditGateway->setEnabled(ipMode == Manual);
    btnDeleteGateway->setEnabled(ipMode == Manual);
}
void AdvancedDialog::setIpList(const QList<QPair<QString, QString>> &list) {
    ipList = list;
    refreshIpTable();
}
void AdvancedDialog::setGatewayList(const QList<QPair<QString, int>> &list) {
    gatewayList = list;
    refreshGatewayTable();
}
void AdvancedDialog::refreshIpTable() {
    if (ipMode == DHCP) {
        ipTable->setRowCount(1);
        ipTable->setItem(0, 0, new QTableWidgetItem("已启用DHCP"));
        ipTable->setItem(0, 1, new QTableWidgetItem(""));
    } else {
        ipTable->setRowCount(ipList.size());
        for (int i = 0; i < ipList.size(); ++i) {
            ipTable->setItem(i, 0, new QTableWidgetItem(ipList[i].first));
            ipTable->setItem(i, 1, new QTableWidgetItem(ipList[i].second));
        }
    }
}
void AdvancedDialog::refreshGatewayTable() {
    if (ipMode == DHCP) {
        // 只显示当前网关，禁用按钮
        gatewayTable->setRowCount(gatewayList.size());
        for (int i = 0; i < gatewayList.size(); ++i) {
            gatewayTable->setItem(i, 0, new QTableWidgetItem(gatewayList[i].first));
            gatewayTable->setItem(i, 1, new QTableWidgetItem(gatewayList[i].second < 0 ? "自动" : QString::number(gatewayList[i].second)));
        }
        btnAddGateway->setEnabled(false);
        btnEditGateway->setEnabled(false);
        btnDeleteGateway->setEnabled(false);
    } else {
        gatewayTable->setRowCount(gatewayList.size());
        for (int i = 0; i < gatewayList.size(); ++i) {
            gatewayTable->setItem(i, 0, new QTableWidgetItem(gatewayList[i].first));
            gatewayTable->setItem(i, 1, new QTableWidgetItem(gatewayList[i].second < 0 ? "自动" : QString::number(gatewayList[i].second)));
        }
        btnAddGateway->setEnabled(true);
        btnEditGateway->setEnabled(true);
        btnDeleteGateway->setEnabled(true);
    }
}
class IpInputDialog : public QDialog {
public:
    QLineEdit *editIp;
    QLineEdit *editMask;
    IpInputDialog(QWidget *parent = nullptr) : QDialog(parent) {
        setWindowTitle("TCP/IP 地址");
        setFixedSize(320, 120);
        QFont normalFont("Microsoft YaHei UI", 9);
        this->setFont(normalFont);
        QVBoxLayout *mainLayout = new QVBoxLayout(this);
        QGridLayout *formLayout = new QGridLayout;
        QLabel *labelIp = new QLabel("IP地址(I):", this);
        labelIp->setFont(normalFont);
        editIp = new QLineEdit(this);
        editIp->setFont(normalFont);
        editIp->setFixedWidth(140);
        QLabel *labelMask = new QLabel("子网掩码(S):", this);
        labelMask->setFont(normalFont);
        editMask = new QLineEdit(this);
        editMask->setFont(normalFont);
        editMask->setFixedWidth(140);
        formLayout->addWidget(labelIp, 0, 0, Qt::AlignRight|Qt::AlignVCenter);
        formLayout->addWidget(editIp, 0, 1);
        formLayout->addWidget(labelMask, 1, 0, Qt::AlignRight|Qt::AlignVCenter);
        formLayout->addWidget(editMask, 1, 1);
        mainLayout->addLayout(formLayout);
        QHBoxLayout *btnLayout = new QHBoxLayout;
        QPushButton *btnOk = new QPushButton("添加(A)", this);
        btnOk->setFont(normalFont);
        QPushButton *btnCancel = new QPushButton("取消", this);
        btnCancel->setFont(normalFont);
        btnLayout->addStretch();
        btnLayout->addWidget(btnOk);
        btnLayout->addWidget(btnCancel);
        mainLayout->addLayout(btnLayout);
        connect(btnOk, &QPushButton::clicked, this, &QDialog::accept);
        connect(btnCancel, &QPushButton::clicked, this, &QDialog::reject);
        // 子网掩码自动填充
        editMask->installEventFilter(this);
    }
protected:
    bool eventFilter(QObject *obj, QEvent *event) override {
        if (obj == editMask && event->type() == QEvent::FocusIn) {
            if (editMask->text().isEmpty()) {
                editMask->setText("255.255.255.0");
            }
        }
        return QDialog::eventFilter(obj, event);
    }
};
void AdvancedDialog::onAddIp() {
    IpInputDialog dlg(this);
    if (dlg.exec() == QDialog::Accepted) {
        QString ip = dlg.editIp->text().trimmed();
        QString mask = dlg.editMask->text().trimmed();
        if (ip.isEmpty() || mask.isEmpty()) {
            QMessageBox::warning(this, "输入错误", "IP地址和子网掩码不能为空");
            return;
        }
        // 简单校验格式
        QRegularExpression ipRegex("^\\d{1,3}(\\.\\d{1,3}){3}$");
        if (!ipRegex.match(ip).hasMatch() || !ipRegex.match(mask).hasMatch()) {
            QMessageBox::warning(this, "输入错误", "请输入合法的IP地址和子网掩码");
            return;
        }
        ipList.append(qMakePair(ip, mask));
        refreshIpTable();
    }
}
void AdvancedDialog::onEditIp() {
    int row = ipTable->currentRow();
    if (row < 0 || ipMode == DHCP) return;
    IpInputDialog dlg(this);
    dlg.editIp->setText(ipList[row].first);
    dlg.editMask->setText(ipList[row].second);
    dlg.setWindowTitle("编辑 TCP/IP 地址");
    QPushButton *okBtn = dlg.findChild<QPushButton*>(QString(), Qt::FindDirectChildrenOnly);
    if (okBtn) okBtn->setText("确定");
    if (dlg.exec() == QDialog::Accepted) {
        QString ip = dlg.editIp->text().trimmed();
        QString mask = dlg.editMask->text().trimmed();
        if (ip.isEmpty() || mask.isEmpty()) {
            QMessageBox::warning(this, "输入错误", "IP地址和子网掩码不能为空");
            return;
        }
        QRegularExpression ipRegex("^\\d{1,3}(\\.\\d{1,3}){3}$");
        if (!ipRegex.match(ip).hasMatch() || !ipRegex.match(mask).hasMatch()) {
            QMessageBox::warning(this, "输入错误", "请输入合法的IP地址和子网掩码");
            return;
        }
        ipList[row].first = ip;
        ipList[row].second = mask;
        refreshIpTable();
    }
}
void AdvancedDialog::onDeleteIp() {
    int row = ipTable->currentRow();
    if (row < 0 || ipMode == DHCP) return;
    if (ipList.size() <= 1) {
        QMessageBox::warning(this, "操作无效", "最少要有一个IP地址，无法删除！");
        return;
    }
    ipList.removeAt(row);
    refreshIpTable();
}
void AdvancedDialog::onAddGateway() {
    // 弹窗输入网关和跃点
    QDialog dlg(this);
    dlg.setWindowTitle("添加默认网关");
    dlg.setFixedSize(360, 170);
    QFont normalFont("Microsoft YaHei UI", 9);
    dlg.setFont(normalFont);
    QVBoxLayout *mainLayout = new QVBoxLayout(&dlg);
    QGridLayout *formLayout = new QGridLayout;
    QLabel *labelGw = new QLabel("网关(G):", &dlg);
    labelGw->setFont(normalFont);
    QLineEdit *editGw = new QLineEdit(&dlg);
    editGw->setFont(normalFont);
    editGw->setFixedWidth(180);
    editGw->setFixedHeight(24);
    // 左对齐，与跃点数编辑框对齐
    formLayout->addWidget(labelGw, 0, 0, Qt::AlignLeft | Qt::AlignVCenter);
    formLayout->addWidget(editGw, 0, 1, Qt::AlignLeft | Qt::AlignVCenter);
    mainLayout->addLayout(formLayout);
    // 分组框：自动跃点+跃点数
    QGroupBox *metricGroup = new QGroupBox("自动跃点(U)", &dlg);
    metricGroup->setFont(normalFont);
    metricGroup->setCheckable(true);
    metricGroup->setChecked(true);
    QGridLayout *metricLayout = new QGridLayout(metricGroup);
    QLabel *labelMetric = new QLabel("跃点数(M):", metricGroup);
    labelMetric->setFont(normalFont);
    QLineEdit *editMetric = new QLineEdit(metricGroup);
    editMetric->setFont(normalFont);
    editMetric->setFixedWidth(180);
    editMetric->setFixedHeight(24);
    metricLayout->addWidget(labelMetric, 0, 0, Qt::AlignLeft | Qt::AlignVCenter);
    metricLayout->addWidget(editMetric, 0, 1, Qt::AlignLeft | Qt::AlignVCenter);
    metricGroup->setLayout(metricLayout);
    mainLayout->addWidget(metricGroup);
    // 自动跃点逻辑
    editMetric->setEnabled(false);
    labelMetric->setEnabled(false);
    QObject::connect(metricGroup, &QGroupBox::toggled, [&](bool checked){
        editMetric->setEnabled(!checked);
        labelMetric->setEnabled(!checked);
    });
    QHBoxLayout *btnLayout = new QHBoxLayout;
    btnLayout->addStretch();
    QPushButton *btnOk = new QPushButton("确定", &dlg);
    QPushButton *btnCancel = new QPushButton("取消", &dlg);
    btnOk->setFont(normalFont);
    btnCancel->setFont(normalFont);
    btnOk->setFixedSize(75, 28);
    btnCancel->setFixedSize(75, 28);
    btnLayout->addWidget(btnOk);
    btnLayout->addWidget(btnCancel);
    mainLayout->addLayout(btnLayout);
    QObject::connect(btnOk, &QPushButton::clicked, &dlg, &QDialog::accept);
    QObject::connect(btnCancel, &QPushButton::clicked, &dlg, &QDialog::reject);
    if (dlg.exec() == QDialog::Accepted) {
        QString gw = editGw->text().trimmed();
        int metric = metricGroup->isChecked() ? -1 : (editMetric->text().trimmed().isEmpty() ? -1 : editMetric->text().toInt());
        if (gw.isEmpty()) {
            QMessageBox::warning(this, "输入错误", "网关地址不能为空");
            return;
        }
        gatewayList.append(qMakePair(gw, metric));
        refreshGatewayTable();
    }
}
void AdvancedDialog::onEditGateway() {
    int row = gatewayTable->currentRow();
    if (row < 0 || ipMode == DHCP) return;
    QDialog dlg(this);
    dlg.setWindowTitle("编辑默认网关");
    dlg.setFixedSize(360, 170);
    QFont normalFont("Microsoft YaHei UI", 9);
    dlg.setFont(normalFont);
    QVBoxLayout *mainLayout = new QVBoxLayout(&dlg);
    QGridLayout *formLayout = new QGridLayout;
    QLabel *labelGw = new QLabel("网关(G):", &dlg);
    labelGw->setFont(normalFont);
    QLineEdit *editGw = new QLineEdit(&dlg);
    editGw->setFont(normalFont);
    editGw->setFixedWidth(180);
    editGw->setFixedHeight(24);
    formLayout->addWidget(labelGw, 0, 0, Qt::AlignLeft | Qt::AlignVCenter);
    formLayout->addWidget(editGw, 0, 1, Qt::AlignLeft | Qt::AlignVCenter);
    mainLayout->addLayout(formLayout);
    // 分组框：自动跃点+跃点数
    QGroupBox *metricGroup = new QGroupBox("自动跃点(U)", &dlg);
    metricGroup->setFont(normalFont);
    metricGroup->setCheckable(true);
    QGridLayout *metricLayout = new QGridLayout(metricGroup);
    QLabel *labelMetric = new QLabel("跃点数(M):", metricGroup);
    labelMetric->setFont(normalFont);
    QLineEdit *editMetric = new QLineEdit(metricGroup);
    editMetric->setFont(normalFont);
    editMetric->setFixedWidth(180);
    editMetric->setFixedHeight(24);
    metricLayout->addWidget(labelMetric, 0, 0, Qt::AlignLeft | Qt::AlignVCenter);
    metricLayout->addWidget(editMetric, 0, 1, Qt::AlignLeft | Qt::AlignVCenter);
    metricGroup->setLayout(metricLayout);
    mainLayout->addWidget(metricGroup);
    // 自动跃点逻辑
    if (gatewayList[row].second < 0) {
        metricGroup->setChecked(true);
        editMetric->setText("");
        editMetric->setEnabled(false);
        labelMetric->setEnabled(false);
    } else {
        metricGroup->setChecked(false);
        editMetric->setText(QString::number(gatewayList[row].second));
        editMetric->setEnabled(true);
        labelMetric->setEnabled(true);
    }
    QObject::connect(metricGroup, &QGroupBox::toggled, [&](bool checked){
        editMetric->setEnabled(!checked);
        labelMetric->setEnabled(!checked);
    });
    QHBoxLayout *btnLayout = new QHBoxLayout;
    btnLayout->addStretch();
    QPushButton *btnOk = new QPushButton("确定", &dlg);
    QPushButton *btnCancel = new QPushButton("取消", &dlg);
    btnOk->setFont(normalFont);
    btnCancel->setFont(normalFont);
    btnOk->setFixedSize(75, 28);
    btnCancel->setFixedSize(75, 28);
    btnLayout->addWidget(btnOk);
    btnLayout->addWidget(btnCancel);
    mainLayout->addLayout(btnLayout);
    QObject::connect(btnOk, &QPushButton::clicked, &dlg, &QDialog::accept);
    QObject::connect(btnCancel, &QPushButton::clicked, &dlg, &QDialog::reject);
    if (dlg.exec() == QDialog::Accepted) {
        QString gw = editGw->text().trimmed();
        int metric = metricGroup->isChecked() ? -1 : (editMetric->text().trimmed().isEmpty() ? -1 : editMetric->text().toInt());
        if (gw.isEmpty()) {
            QMessageBox::warning(this, "输入错误", "网关地址不能为空");
            return;
        }
        gatewayList[row].first = gw;
        gatewayList[row].second = metric;
        refreshGatewayTable();
    }
}
void AdvancedDialog::onDeleteGateway() {
    int row = gatewayTable->currentRow();
    if (row < 0 || ipMode == DHCP) return;
    gatewayList.removeAt(row);
    refreshGatewayTable();
}
void AdvancedDialog::onAutoMetricToggled(bool checked) {
    editMetric->setEnabled(!checked);
    autoMetric = checked;
}
QList<QPair<QString, QString>> AdvancedDialog::getIpList() const { return ipList; }
QList<QPair<QString, int>> AdvancedDialog::getGatewayList() const { return gatewayList; }
bool AdvancedDialog::isAutoMetric() const { return autoMetric; }
int AdvancedDialog::getInterfaceMetric() const { return editMetric->text().toInt(); } 